


package jnpf.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.model.flowengine.FlowModel;
import jnpf.engine.service.FlowDynamicService;
import jnpf.entity.DocumentEntity;
import jnpf.entity.MzCompilationprojectEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.model.mzcompilationproject.MzCompilationprojectForm;
import jnpf.model.mzcompilationproject.MzCompilationprojectInfoVO;
import jnpf.model.mzcompilationproject.MzCompilationprojectListVO;
import jnpf.model.mzcompilationproject.MzCompilationprojectPagination;
import jnpf.permission.entity.UserEntity;
import jnpf.service.DocumentService;
import jnpf.service.MzCompilationprojectService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 采编项目管理
 *
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2023-12-10
 */
@Slf4j
@RestController
@Tag(name = "mzCompilationproject", description = "example")
@RequestMapping("/api/example/MzCompilationproject")
public class MzCompilationprojectController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ConvertUtils convertUtils;

    @Autowired
    private MzCompilationprojectService mzCompilationprojectService;
    @Autowired
    private FlowDynamicService flowDynamicService;
    @Autowired
    private DocumentService documentService;


    /**
     * 列表
     *
     * @param mzCompilationprojectPagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody MzCompilationprojectPagination mzCompilationprojectPagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        List<MzCompilationprojectEntity> list = mzCompilationprojectService.getList(mzCompilationprojectPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<MzCompilationprojectListVO> listVO = JsonUtil.getJsonToList(list, MzCompilationprojectListVO.class);
        for (MzCompilationprojectListVO mzCompilationprojectVO : listVO) {
            ActionResult info = info(mzCompilationprojectVO.getId());
            Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
            mzCompilationprojectVO.setProjectname_name(mzCompilationprojectVO.getProjectname());

            mzCompilationprojectVO.setProjectcode_name(mzCompilationprojectVO.getProjectcode());

            mzCompilationprojectVO.setAchievementtype_name(generaterSwapUtil.getDicName(mzCompilationprojectVO.getAchievementtype(), "502916754670878725"));

            mzCompilationprojectVO.setAffiliatedcollege_name(generaterSwapUtil.comSelectValues(mzCompilationprojectVO.getAffiliatedcollege(),false));

            mzCompilationprojectVO.setGainType_name(generaterSwapUtil.getDicName(mzCompilationprojectVO.getGainType(), "534298679746494597"));

            mzCompilationprojectVO.setProjectcompletionperson_name(generaterSwapUtil.userSelectValues(mzCompilationprojectVO.getProjectcompletionperson()));

            mzCompilationprojectVO.setProjectstart_name(mzCompilationprojectVO.getProjectstart() != null ?
                    new Date(mzCompilationprojectVO.getProjectstart()) : null);

            mzCompilationprojectVO.setProjectend_name(mzCompilationprojectVO.getProjectend() != null ?
                    new Date(mzCompilationprojectVO.getProjectend()) : null);

            mzCompilationprojectVO.setIsenable_name(generaterSwapUtil.switchSelectValue(mzCompilationprojectVO.getIsenable(), "开", "关"));


            mzCompilationprojectVO.setCoverurl_id(mzCompilationprojectVO.getCoverurl_name());
            if(StringUtil.isNotEmpty(mzCompilationprojectVO.getCoverurl())){
                DocumentEntity doc = documentService.getInfo(mzCompilationprojectVO.getCoverurl());
                mzCompilationprojectVO.setCoverurl_name(convertUtils.DocumentConvertUrl(doc.getFileExtension(),doc.getFilePath()));

            }
            if(StringUtil.isNotEmpty(mzCompilationprojectVO.getVideourl())){
                DocumentEntity doc = documentService.getInfo(mzCompilationprojectVO.getVideourl());
                mzCompilationprojectVO.setVideourl_name(convertUtils.DocumentConvertUrl(doc.getFileExtension(),doc.getFilePath()));
            }

            mzCompilationprojectVO.setVideourl_id(mzCompilationprojectVO.getVideourl_name());

            mzCompilationprojectVO.setSort_name(generaterSwapUtil.getDecimalStr(mzCompilationprojectVO.getSort()));

            mzCompilationprojectVO.setBriefintroduction_name(mzCompilationprojectVO.getBriefintroduction());

            mzCompilationprojectVO.setIscomplete_name(generaterSwapUtil.switchSelectValue(mzCompilationprojectVO.getIscomplete(), "是", "否"));

            mzCompilationprojectVO.setState_name(generaterSwapUtil.getDicName(mzCompilationprojectVO.getState(), "505004425010479109"));

            //子表数据转换
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(mzCompilationprojectPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 审批提交
     *
     * @param mzCompilationprojectPagination
     * @return
     */
    @PostMapping("/approvalSubmission")
    @Transactional
    @Operation(summary = "审批提交")
    public ActionResult approvalSubmission(@RequestBody MzCompilationprojectPagination mzCompilationprojectPagination) throws DataException, WorkFlowException {
        if (StringUtil.isEmpty(mzCompilationprojectPagination.getMainId())) {
            return ActionResult.fail("主键不能为空！");
        }
        String[] approvalIds = mzCompilationprojectPagination.getMainId().split(",");
        Integer count = 0;
        for (String id : approvalIds) {
            MzCompilationprojectEntity compilationprojectEntity = mzCompilationprojectService.getInfo(id);
            if (StringUtil.isNull(compilationprojectEntity)) {
                return ActionResult.fail("未查询到采编项目信息！");
            } else if (!"cg".equals(compilationprojectEntity.getState())) {
                return ActionResult.fail("项目正在审批中！");
            }
            UserInfo userInfo = userProvider.get();
            FlowModel flowModel = new FlowModel();
            flowModel.setFlowId("517788466382152645");//v1:516590667909038213
            flowModel.setStatus("0");
            flowModel.setFlowUrgent(1);
            flowModel.setUserInfo(userInfo);
            flowModel.setId(id);
            flowModel.setTaskId(id);
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("projectname", compilationprojectEntity.getProjectname());
            map.put("projectcode", compilationprojectEntity.getProjectcode());

            map.put("achievementtype", compilationprojectEntity.getAchievementtype());
            map.put("gainType", compilationprojectEntity.getGainType());
            map.put("affiliatedcollege", compilationprojectEntity.getAffiliatedcollege());
            map.put("projectcompletionperson", compilationprojectEntity.getProjectcompletionperson());
            map.put("projectstart", compilationprojectEntity.getProjectstart());
            map.put("projectend", compilationprojectEntity.getProjectend());
            map.put("isenable", compilationprojectEntity.getIsenable());
            map.put("sort", compilationprojectEntity.getSort());
            map.put("briefintroduction", compilationprojectEntity.getBriefintroduction());
            map.put("coverurl", compilationprojectEntity.getCoverurl());
            map.put("videourl", compilationprojectEntity.getVideourl());
            map.put("iscomplete", "1");//表示项目已完成
            map.put("state", compilationprojectEntity.getState());
            map.put("isSpread", compilationprojectEntity.getIsSpread());

            flowModel.setFormData(map);
            flowDynamicService.batchCreateOrUpdate(flowModel);
//            compilationprojectEntity.setFlowid("504643883850793413");
            compilationprojectEntity.setState("spz");
            mzCompilationprojectService.updateById(compilationprojectEntity);
            count++;
        }
        //String msg = FlowStatusEnum.save.getMessage().equals(flowModel.getStatus()) ? MsgCode.SU002.get() : MsgCode.SU006.get();
        return ActionResult.success("已审批" + count + "条数据");
    }

    /**
     * 创建
     *
     * @param mzCompilationprojectForm
     * @return
     */
    @PostMapping
    @Transactional
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid MzCompilationprojectForm mzCompilationprojectForm) throws DataException {
        String b = mzCompilationprojectService.checkForm(mzCompilationprojectForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        GeneraterSwapUtil.swapDatetime(mzCompilationprojectForm);
        MzCompilationprojectEntity entity = JsonUtil.getJsonToBean(mzCompilationprojectForm, MzCompilationprojectEntity.class);
        entity.setId(mainId);
        entity.setProjectcode(generaterSwapUtil.getBillNumber("CBXM", false));
        entity.setState("cg");
        entity.setIscomplete("0");
        entity.setCreatortime(new Date());
        entity.setCreatoruserid(userInfo.getUserId());
        mzCompilationprojectService.save(entity);


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult<MzCompilationprojectInfoVO> info(@PathVariable("id") String id) {
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(id);
        MzCompilationprojectInfoVO vo = JsonUtil.getJsonToBean(entity, MzCompilationprojectInfoVO.class);

        //子表
        if (StringUtil.isNotEmpty(vo.getCoverurl())) {
            DocumentEntity documentEntity = documentService.getInfo(vo.getCoverurl());
            vo.setCoverurlname(documentEntity.getFullName());
        }
        if (StringUtil.isNotEmpty(vo.getVideourl())) {
            DocumentEntity documentEntity = documentService.getInfo(vo.getVideourl());
            vo.setVideourlname(documentEntity.getFullName());
        }
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<MzCompilationprojectInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(id);
        MzCompilationprojectInfoVO vo = JsonUtil.getJsonToBean(entity, MzCompilationprojectInfoVO.class);

        //子表数据转换

        //附表数据转换

//添加到详情表单对象中
        vo.setProjectname(vo.getProjectname());

        vo.setProjectcode(vo.getProjectcode());

        vo.setAchievementtype(generaterSwapUtil.getDicName(vo.getAchievementtype(), "502916754670878725"));

        vo.setGainType(generaterSwapUtil.getDicName(vo.getGainType(), "534298679746494597"));

        vo.setAffiliatedcollege(generaterSwapUtil.comSelectValues(vo.getAffiliatedcollege(),false));
        vo.setProjectcompletionperson(generaterSwapUtil.userSelectValues(vo.getProjectcompletionperson()));

        vo.setProjectstart(vo.getProjectstart());

        vo.setProjectend(vo.getProjectend());

        vo.setIsenable(generaterSwapUtil.switchSelectValue(vo.getIsenable(), "开", "关"));


        vo.setCoverurl_id(vo.getCoverurl());

        //Map<String, Object> coverurlMap = new HashMap<>();
        //vo.setCoverurl(generaterSwapUtil.swapRelationFormValue("billRuleField119", vo.getCoverurl(), "293732572549126981", coverurlMap));
        if (StringUtil.isNotEmpty(vo.getCoverurl())) {
            DocumentEntity documentEntity = documentService.getInfo(vo.getCoverurl());
            vo.setCoverurlname(documentEntity.getFullName());
        }

        vo.setVideourl_id(vo.getVideourl());

        //Map<String, Object> videourlMap = new HashMap<>();
        //vo.setVideourl(generaterSwapUtil.swapRelationFormValue("name", vo.getVideourl(), "395179260593052933", videourlMap));
        if (StringUtil.isNotEmpty(vo.getVideourl())) {
            DocumentEntity documentEntity = documentService.getInfo(vo.getVideourl());
            vo.setVideourlname(documentEntity.getFullName());
        }
        vo.setSort_name(generaterSwapUtil.getDecimalStr(vo.getSort()));

        vo.setBriefintroduction(vo.getBriefintroduction());

        vo.setIscomplete(vo.getIscomplete());

        vo.setState(vo.getState());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param mzCompilationprojectForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid MzCompilationprojectForm mzCompilationprojectForm) throws DataException {
        String b = mzCompilationprojectService.checkForm(mzCompilationprojectForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(id);
        if (entity != null) {
            GeneraterSwapUtil.swapDatetime(mzCompilationprojectForm);
            MzCompilationprojectEntity subentity = JsonUtil.getJsonToBean(mzCompilationprojectForm, MzCompilationprojectEntity.class);
            boolean b1 = mzCompilationprojectService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 更新项目完成状态
     * @param mzCompilationprojectForm
     * @return
     */
    @PutMapping("/isComplete")
    @Transactional
    @Operation(summary = "更新项目完成状态")
    public ActionResult isComplete(@RequestBody @Valid MzCompilationprojectForm mzCompilationprojectForm) throws DataException {

        if (StringUtil.isEmpty(mzCompilationprojectForm.getId())) {
            return ActionResult.fail("主键不能为空！");
        }
        UserInfo userInfo = userProvider.get();
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(mzCompilationprojectForm.getId());
        if (entity != null) {
            entity.setIscomplete("1");
            boolean b1 = mzCompilationprojectService.updateById(entity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(id);
        if (entity != null) {
            mzCompilationprojectService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 审批挂网
     *
     * @param mzCompilationprojectForm
     * @return
     */
    @Operation(summary = "挂网")
    @PostMapping("/spread")
    @Transactional
    public ActionResult spread(MzCompilationprojectForm mzCompilationprojectForm) {
        if (StringUtil.isEmpty(mzCompilationprojectForm.getId())) {
            return ActionResult.success("主键不能为空");
        }
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(mzCompilationprojectForm.getId());
        if (entity != null) {
            if ("1".equals(entity.getIscomplete())) {
                if ("spwc".equals(entity.getState())) {
                    entity.setIsSpread("1");
                    entity.setState("ygw");
                    mzCompilationprojectService.updateById(entity);
                } else {
                    return ActionResult.success("状态不是审批完成！");
                }
            } else {
                return ActionResult.success("项目未完成！");
            }
        }
        return ActionResult.success("成功挂网！");
    }

    /**
     * 审批改变状态(审批中)
     *
     * @param mzCompilationprojectForm
     * @return
     */
    @Operation(summary = "审批改变状态(审批中)")
    @PostMapping("/changeStateSpz")
    public ActionResult changeState(@RequestBody MzCompilationprojectForm mzCompilationprojectForm) {
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(mzCompilationprojectForm.getId());
        if (entity != null) {
            if ("cg".equals(entity.getState())) {
                if ("spz".equals(entity.getState())) {
                    return ActionResult.success("状态已是审批中");
                }
                GeneraterSwapUtil.swapDatetime(mzCompilationprojectForm);
                MzCompilationprojectEntity subentity = JsonUtil.getJsonToBean(mzCompilationprojectForm, MzCompilationprojectEntity.class);
                entity.setState("spz");
                mzCompilationprojectService.update(entity.getId(), entity);
            }
        }
        return ActionResult.success("状态已改变");
    }

    /**
     * 审批改变状态(审批完成)
     *
     * @param mzCompilationprojectForm
     * @return
     */
    @Operation(summary = "审批改变状态(审批完成)")
    @PostMapping("/changeStateSpwc")
    public ActionResult changeStateSpwc(@RequestBody MzCompilationprojectForm mzCompilationprojectForm) {
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(mzCompilationprojectForm.getId());
        if (entity != null) {
            if ("spz".equals(entity.getState())) {
                if ("spwc".equals(entity.getState())) {
                    return ActionResult.success("状态已是审批完成");
                }
                entity.setState("spwc");
                mzCompilationprojectService.updateById(entity);
            }
        }
        return ActionResult.success("状态已改变");
    }

    /**
     * 审批改变状态(撤回)
     *
     * @param mzCompilationprojectForm
     * @return
     */
    @Operation(summary = "审批改变状态(撤回)")
    @PostMapping("/changeStateCh")
    public ActionResult changeStateCh(MzCompilationprojectForm mzCompilationprojectForm) {
        MzCompilationprojectEntity entity = mzCompilationprojectService.getInfo(mzCompilationprojectForm.getId());
        if (entity != null) {
            entity.setIscomplete("0");
            entity.setState("cg");
            mzCompilationprojectService.updateById(entity);
        }
        return ActionResult.success("状态已改变");
    }


}
